package com.comecrd.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * JSON数组类型处理器，用于处理List<String>类型的字段
 */
@MappedTypes({List.class})
@MappedJdbcTypes(JdbcType.VARCHAR)
public class JsonArrayTypeHandler extends BaseTypeHandler<List<String>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
        // 将List<String>转换为JSON字符串
        String json = JSON.toJSONString(parameter);
        ps.setString(i, json);
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        // 从ResultSet获取JSON字符串并转换为List<String>
        String json = rs.getString(columnName);
        return parseJsonArray(json);
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        // 从ResultSet获取JSON字符串并转换为List<String>
        String json = rs.getString(columnIndex);
        return parseJsonArray(json);
    }

    @Override
    public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        // 从CallableStatement获取JSON字符串并转换为List<String>
        String json = cs.getString(columnIndex);
        return parseJsonArray(json);
    }

    /**
     * 解析JSON字符串为List<String>
     * @param json JSON字符串
     * @return List<String>
     */
    private List<String> parseJsonArray(String json) {
        if (json == null || json.isEmpty()) {
            return new ArrayList<>();
        }
        try {
            JSONArray jsonArray = JSON.parseArray(json);
            List<String> list = new ArrayList<>(jsonArray.size());
            for (int i = 0; i < jsonArray.size(); i++) {
                list.add(jsonArray.getString(i));
            }
            return list;
        } catch (Exception e) {
            throw new RuntimeException("解析JSON数组失败", e);
        }
    }
}